package com.xysd.express.util.http;

import android.util.Log;

import com.xysd.express.app.App;
import com.xysd.express.bean.User;
import com.xysd.express.util.JSONParser;
import com.xysd.express.util.ToastUtil;

import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.Map;


/**
 * Created by donghui on 2017/5/25.网络请求工具类，基于xutil3.0
 */
public class HttpRequestUtil {
    public static final String URL = "";
    static HttpCallBack mHttpCallBack;

    /**
     * 发送请求
     *
     * @param method        请求类型 Post或Get
     * @param url           请求地址
     * @param map           请求参数
     * @param mHttpCallBack 回调接口
     */
    public static void send(HttpMethod method,
                            String url, Map<String, Object> map, HttpCallBack mHttpCallBack) {
        HttpRequestUtil.mHttpCallBack = mHttpCallBack;

//        url = ConstantParser.HTTP_URI + url;
        url = ConstantParser.HTTP_URI_LOCALE + url;
        Log.i("url", url);
        RequestParams params = parserMap(method, url, map);
        params.setConnectTimeout(8000);
        if (method == HttpMethod.POST) {
            x.http().post(params, callback);
        } else if (method == HttpMethod.GET) {
            x.http().get(params, callback);
        }

    }


    /**
     * 解析map集合 并封装到RequestParams对象
     *
     * @param map
     * @return
     */
    private static RequestParams parserMap(HttpMethod method, String url,
                                           Map<String, Object> map) {


        // 设置请求参数
        RequestParams params = new RequestParams(url);

        //添加请求头
        params.addHeader("AppVersionCode", App.versionCode);
        Log.i("RequestHeader","AppVersionCode:"+App.versionCode);
        if (User.getInstance().isLogin){
            params.addHeader("AUTH_UID",User.getInstance().UserId+"");
            params.addHeader("AUTH_TIMESTAMP",User.getInstance().Timestamp+"");
            params.addHeader("AUTH_KEY",User.getInstance().AuthKey);
            Log.i("RequestHeader","AUTH_UID:"+User.getInstance().UserId+"");
            Log.i("RequestHeader","AUTH_TIMESTAMP:"+User.getInstance().Timestamp+"");
            Log.i("RequestHeader","AUTH_KEY:"+User.getInstance().AuthKey+"");

        }

        if (map == null || map.size() <= 0) {
            return params;
        }
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Log.i("params", "key= " + entry.getKey() + " and value= "
                    + entry.getValue());
            if (entry.getValue() instanceof File) {
                params.addBodyParameter(entry.getKey(),
                        (File) entry.getValue());
            } else if (method == HttpMethod.POST) {
                params.addBodyParameter(entry.getKey(), entry.getValue() + "");
            } else if (method == HttpMethod.GET) {
                params.addQueryStringParameter(entry.getKey(), entry.getValue()
                        + "");
            }
        }


        return params;
    }


    /**
     * xutil的网络请求回调
     */
    public static Callback.CommonCallback<String> callback = new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            mHttpCallBack.onSuccess(result);
            String code = JSONParser.getStringFromJsonString("Status", result);
//            if ("3".equals(code)) {
//                Log.d("未登录", "status=3");
//                EventBus.getDefault().post(new LogoutEvent());//通知baseActivity未登录
//            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            mHttpCallBack.onFailure(ex.toString() + "      isOnCallback:" + isOnCallback);
            //ToastUtil.show( "网络请求失败");
        }

        @Override
        public void onCancelled(CancelledException cex) {
            mHttpCallBack.onFailure(cex.toString() + "请求取消");
            ToastUtil.show( "网络请求取消");
        }

        @Override
        public void onFinished() {//成功或失败都会调用此方法
            Log.i("onFinished", "请求结束");
        }
    };


    /**
     * 上传图片（加请求头）
     */

    public static void upload(HttpMethod method,
                              String url, Map<String, Object> map, HttpCallBack mHttpCallBack) {
        HttpRequestUtil.mHttpCallBack = mHttpCallBack;

        url = ConstantParser.HTTP_URI + url;
        Log.i("url", url);
        RequestParams params = parserMap(method, url, map);
        params.setMultipart(true);
        params.addHeader("Content-Type", "multipart/form-data");
        if (method == HttpMethod.POST) {
            x.http().post(params, callback);
        } else if (method == HttpMethod.GET) {
            x.http().get(params, callback);
        }

    }





}
